<template>
  <div>
    <el-form-item :label="props.label">
      <el-select
        v-model="value"
        :loading="loading"
        :multiple="props.isMultiple"
        :placeholder="props.placeholder"
        :remote-method="remoteMethod"
        :size="props.size"
        filterable
        remote
        remote-show-suffix
        reserve-keyword
        style="width: 100%"
      >
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </el-form-item>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from "vue";
import { requestSysDictionaryGetOptions } from "@/api/modules/sysDictionary";
import { ResultData } from "@/api/interface";
import { DicOption } from "@/api/interface/SysDictionary/DicOption";

const options = ref<DicOption[]>([]);
const value = ref([]);
const loading = ref(false);

const props = defineProps({
  //字典的key
  dicKey: {
    type: String,
    required: true
  },
  //标签
  label: {
    type: String,
    required: true
  },
  size: {
    type: String,
    required: false,
    default: "default"
  },
  placeholder: {
    type: String,
    required: false,
    default: "输入后进行搜索"
  },
  //是否允许多选
  isMultiple: {
    type: Boolean,
    required: false,
    default: false //默认不允许多选
  },
  //默认值
  defaultValues: {
    type: Array<DicOption>,
    required: false,
    default: []
  }
});

onMounted(() => {
  if (props.defaultValues.length > 0) {
    value.value = props.defaultValues;
  }
});

watch(
  () => props.defaultValues,
  (newVal: DicOption[], oldVal: DicOption[]) => {
    if (newVal && newVal.length > 0) {
      value.value = props.defaultValues;
    }
  }
);
//获取当前选中文本
const GetValue = () => {
  return value.value;
};

const emit = defineEmits(["valueChange"]);

watch(
  () => value.value,
  (newVal: any, oldVal: any) => {
    //值改变时通知父组件,newVal的类型：isMultiple =true时是一个数组，否则是一个值
    emit("valueChange", newVal);
  }
);
defineExpose({ GetValue });

//远程搜索方法触发
const remoteMethod = (searchText: string) => {
  if (searchText == "") {
    return;
  }

  //远程搜索方法
  requestSysDictionaryGetOptions(props.dicKey, searchText)?.then((res: ResultData) => {
    if (res.data) {
      options.value = res.data;
    } else {
      options.value = [];
    }
  });
};
</script>
